#include <httplib.h>
// #include <jsoncpp/json/json.h>
#include "./searcher.hpp"

const std::string input = "./data/output/raw.txt";
const std::string root_path = "./wwwroot";
const int port = 9099;

int main(int argc, char **argv){
    std::string input = "./data/output/raw.txt";
    std::string forward_path  = "./data/index/forward.index";
    std::string inverted_path = "./data/index/inverted.index";
    bool force_build = false;
    for(int i = 1; i < argc; ++i){
        std::string arg = argv[i];
        if(arg == "--rebuild" || arg == "-r"){
            force_build = true;
        }
        else if (arg == "--fwd" && i + 1 < argc) {
            forward_path  = argv[++i];   // 取下一个参数
        }
        else if (arg == "--inv" && i + 1 < argc) {
            inverted_path = argv[++i];
        }
        else {
            input = argv[i];
        }
    }

    Searcher search;
    auto t0 = std::chrono::steady_clock::now();
    search.InitSearcher(input,force_build, forward_path, inverted_path);
    auto t1 = std::chrono::steady_clock::now();
    NORM_LOG("Index Built, cost %ld ms\n", std::chrono::duration_cast<std::chrono::milliseconds>(t1-t0).count());
    httplib::Server svr;
    svr.set_base_dir(root_path);

    svr.Get("/s", [&search](const httplib::Request &req, httplib::Response &rsp){
        if(!req.has_param("word")){
            rsp.set_content("没有搜索关键字", "text/plain; charset=utf-8");
            return;
        }
        std::string word = req.get_param_value("word");
        NORM_LOG("用户在搜索：%s\n",word.c_str());
        std::string json_str;
        search.Search(word, &json_str);
        rsp.set_content(json_str, "application/json");
    });
    auto t2 = std::chrono::steady_clock::now();
    NORM_LOG("Server Listen on %d, built cost %ld ms\n", port, std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count());
    svr.listen("0.0.0.0", port);
    return 0;
}